﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using DataModel.DBService.Impl;
using DataModel.Entity;

namespace DataModel.DBService
{
    public class UserService : RepositoryBase<sc_user>
    {

        public UserService()
        {

        }

        public User Login(string username, string password)
        {
            try
            {
                using (ProductDBContext context = new ProductDBContext())
                {
                    var result = from u in context.Set<sc_user>()
                                 where u.ACCOUNT == username && u.PASSWORD == password
                                 select u;
                    if (result.Any())
                    {
                        return Convert2Dto(result.FirstOrDefault());
                    }
                }
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
                throw;
            }
            return null;
        }

        public User AddUser(User user)
        {
            using (ProductDBContext context = new ProductDBContext())
            {
                sc_user entity = Convert2Entity(user);
                context.Set<sc_user>().Add(entity);
                context.SaveChanges();
                user.id = entity.ID;
                return user;
            }
        }

        private sc_user Convert2Entity(User user)
        {
            sc_user entity = new sc_user
            {
                ACCOUNT = user.account,
                DISPLAYNAME = user.displayName,
                PASSWORD = user.passWord,
                CREATETIME = DateTime.Now
            };
            return entity;
        }

        private User Convert2Dto(sc_user entity)
        {
            if (entity != null)
            {
                return new User
                {
                    id = entity.ID,
                    account = entity.ACCOUNT,
                    displayName = entity.DISPLAYNAME,
                    passWord = entity.PASSWORD
                };
            }
            return null;
        }
    }
}
